<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>应收报表</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form layout="inline" :model="form" style="margin-top:0px;">
        <a-form-item label="客户名称">
          <a-input v-model="form.custNameLike" />
        </a-form-item>
        <a-form-item label="年月">
          <!-- <a-range-picker
            :mode="['month', 'month']"
            format="YYYY-MM"
            @change="timeChange"
            @onPanelChange="test(v)"
            style="width:300px"
          >
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>-->
          <a-range-picker
            format="YYYY-MM"
            :value="value"
            :mode="mode2"
            @panelChange="handlePanelChange2"
            @change="handleChange"
          />
        </a-form-item>
        <a-form-item label="所属部门">
          <a-tree-select
            class="selectInputWidth"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
            placeholder="请选择"
            @change="onChangeTree"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="所属销售">
          <a-select v-model="form.sellerId" class="selectInputWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="check">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="excelExport">导出Excel</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        style="margin-top:25px;"
        :pagination="pagination"
        :row-key="(record,index) => index"
      >
        <template slot="money" slot-scope="text, record">
          <span
            :style="record.currencyType === 'CNY' ? '': 'color:orange'"
          >{{record.currencyType === 'CNY' ? record.receivableAmount.toFixed(2) : `$${record.receivableAmount.toFixed(2)}`}}</span>
        </template>
        <span slot="do" slot-scope="record" :style="'display: flex; align-items: center;'">
          <a @click="detail(record)">详情</a>
        </span>
      </a-table>
    </div>
  </div>
</template>
<script>
import store from 'store'
import { querySellerDown, queryDeptDown } from '@/api'
import { queryReceivableReportList } from '@/api/dataBI'
import { commonExport } from '@/api/request'
import moment from 'moment'
const deptData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '客户名称',
    dataIndex: 'custName',
    width: 300,
    ellipsis: true
  },
  {
    title: '所属部门',
    dataIndex: 'department'
  },
  {
    title: '所属销售',
    dataIndex: 'seller'
  },
  {
    title: '年月',
    dataIndex: 'receivableMonth'
  },
  {
    title: '应收金额（元）',
    dataIndex: 'receivableAmount',
    scopedSlots: {
      customRender: 'money'
    }
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'do'
    }
  }
]
export default {
  data () {
    return {
      deptTreeData: [],
      sellers: [],
      value: [],
      mode2: ['month', 'month'],
      form: {
        custNameLike: '',
        deptId: '',
        sellerId: '',
        startDate: '',
        endDate: ''
      },
      pageNum: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns,
      pagination: {}
    }
  },
  methods: {
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      queryDeptDown(e).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      querySellerDown({ ...sellerData, deptId }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '请选择'
            v.uiId = ''
          }
          return v
        })
      })
    },
    containerListRequest (e) {
      this.loading = true
      queryReceivableReportList(e)
        .then(res => {
          this.$route.meta.s = e
          // store.set('accountsReceivableStartDate', e.startDate)
          // store.set('accountsReceivableEndDate', e.endDate)
          this.data = res.data.list
          let currentPage = this.pageNum
          this.pagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.containerListRequest(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.containerListRequest(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => {})
    },
    handleChange (value) {
      // // console.log(value)
      this.value = value
      this.form.startDate = value[0]
      this.form.endDate = value[1]
    },
    handlePanelChange2 (value, mode) {
      // // console.log(mode)
      this.value = value
      this.form.startDate = moment(value[0]).format('YYYY-MM')
      this.form.endDate = moment(value[1]).format('YYYY-MM')
      this.mode2 = [
        mode[0] === 'date' ? 'month' : mode[0],
        mode[1] === 'date' ? 'month' : mode[1]
      ]
    },
    check () {
      this.pageNum = 1
      this.containerListRequest({
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    excelExport () {
      const newColumns = [
        {
          title: '客户名称',
          dataIndex: 'custName'
        },
        {
          title: '所属部门',
          dataIndex: 'department'
        },
        {
          title: '所属销售',
          dataIndex: 'seller'
        },
        {
          title: '年月',
          dataIndex: 'receivableMonth'
        },
        {
          title: '应收金额（元）',
          dataIndex: 'receivableAmount'
        },
        {
          title: '币种',
          dataIndex: 'currencyType'
        }
      ]
      commonExport('containerReport/exportReceivableReportList', {
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: newColumns
      })
    },
    detail (e) {
      // console.log(e)
      store.set('jhStartDate', e.receivableMonth)
      store.set('jhEndDate', e.receivableMonth)
      store.set('jhCurrencyType', e.currencyType)
      this.$router.push(`accountsReceivable/detail/${e.custId}`)
    }
  },
  mounted () {
    this.initDept(deptData) // 所属部门
    this.initSellerDown() // 所属销售
    let originObj = this.$route.meta.s
    this.listAssign(this.form, originObj)
    if (originObj) {
      this.pageSize = originObj.pageSize
      this.pageNum = originObj.pageNum
      this.form.startDate = originObj.startDate
      this.form.endDate = originObj.endDate
      if (originObj.startDate) {
        this.value = [moment(originObj.startDate), moment(originObj.endDate)]
      } else {
        this.value = []
      }
    }
    this.containerListRequest({
      ...this.form,
      pageNum: this.pageNum,
      pageSize: this.pageSize
    })
  },
  beforeRouteEnter (to, from, next) {
    if (from.name !== 'JHaccountsReceivableDetail' || to.query.f !== '1') {
      to.meta.s = null
    }
    next()
  }
}
</script>

<style lang="less" scoped>
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;
}
</style>
